package com.swipemaster.network.task;

import android.os.AsyncTask;

import com.swipemaster.common.Global;
import com.swipemaster.common.Prefs;
import com.swipemaster.network.Network;
import com.swipemaster.record.RecordsManager;

/** Task for asynchronous sending user stats to server */
public class SendStatsTask extends AsyncTask<Void, Void, Void>
{
	/** Number of played games between sending user stats to server */
	private static final int GAMES_PLAYED_BETWEEN_SENDING_STATS = 10;

	/** Statistics should be sent only once in a while */
	public static boolean shouldSendStats()
	{
		final int lastSentGamesCounter = Global.app.prefs.getInt(Prefs.GAMES_PLAYED_WHEN_STATS_SENT_KEY, 0);
		final int gamesPlayed = RecordsManager.getGamesPlayed();
		return (gamesPlayed - lastSentGamesCounter) >= GAMES_PLAYED_BETWEEN_SENDING_STATS;
	}

	@Override
	protected Void doInBackground(Void... params)
	{
		try
		{
			Network.sendStats();
			final int gamesPlayed = RecordsManager.getGamesPlayed();
			Global.app.prefs.putObject(Prefs.GAMES_PLAYED_WHEN_STATS_SENT_KEY, gamesPlayed);
		}
		catch (final Exception e)
		{
			// thats ok, we will try next time when internet is back
			e.printStackTrace();
		}
		return null;
	}

}
